package com.qf.p1.service.impl;

import com.qf.p1.dao.CourseDao;
import com.qf.p1.dao.CourseMapper;
import com.qf.p1.dao.UserDao;
import com.qf.p1.model.*;
import com.qf.p1.service.CourseService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 课程的业务逻辑实现
 * @version v1.0.0
 * @Description:
 * @author: 姜红凯
 * @date: 2022.04.06
 * @since 1.0
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Resource
    private CourseDao courseDao;

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private UserDao userDao;

    @Override
    public List<CourseTname> pageData(Integer pageNo, Integer pageSize,String likeName) {
        int startPosition=(pageNo-1)*pageSize;
        likeName="%"+likeName+"%";
        return courseMapper.selectByPageNo(startPosition,pageSize,likeName);
    }

    @Override
    public int pageCount(Integer pageSize,String likeName) {
        CourseExample example=new CourseExample();
        CourseExample.Criteria criteria=example.createCriteria();
        likeName="%"+likeName+"%";
        criteria.andNameLike(likeName);
        int count= (int) courseDao.countByExample(example);
        return count/pageSize+(count%pageSize==0?0:1);
    }

    @Override
    public int deleteCourse(Integer cid) {

        return courseDao.deleteByPrimaryKey(cid);
    }

    @Override
    public int addCourse(String name, String teacherName, Integer sMax) {
        Integer tid=null;
        UserExample example=new UserExample();
        UserExample.Criteria criteria=example.createCriteria();
        criteria.andUsernameEqualTo(teacherName);
        List<User> users = userDao.selectByExample(example);
        if (users!=null&&users.size()>0){
            tid=users.get(0).getId();
        }
        Course course=new Course();
        course.setName(name);
        course.setTid(tid);
        course.setsMax(sMax);
        course.setsSum(0);
        return courseDao.insertSelective(course);
    }

    @Override
    public int updateCourse(Integer cid, String name, String teacherName) {
        Integer tid=null;
        UserExample example=new UserExample();
        UserExample.Criteria criteria=example.createCriteria();
        criteria.andUsernameEqualTo(teacherName);
        List<User> users = userDao.selectByExample(example);
        if (users!=null&&users.size()>0){
            tid=users.get(0).getId();
        }
        Course course=new Course();
        //where条件
        course.setId(cid);
        //set数据
        course.setName(name);
        course.setTid(tid);

        return courseDao.updateByPrimaryKeySelective(course);
    }

    @Override
    public List<User> findUserByCid(Integer cid) {
        List<User> users = courseMapper.selectUserByCid(cid);
        return users;
    }
}
